#!/bin/bash
#
# Init file for primes daemon
#
# chkconfig: 45 95 15
# description: Primes daemon
#
# processname: generate-primes.rb
# pidfile: /var/run/primes.pid

# source function library
. /etc/rc.d/init.d/functions

RETVAL=0
prog=generate-primes.rb

# Some functions to make the below more readable

USER=aws
BIN=/home/$USER/primes
PROG=$BIN/$prog
LOG=/var/log/primes.log
PID_FILE=/var/run/primes.pid
LOCK_FILE=/var/lock/subsys/primes

start() {
	echo -n $"Starting $prog: "
	su $USER -c "echo `date` \" Starting\" >>$LOG"
	daemon --user $USER "ruby $PROG" "$LOG &" && success || failure
	myPid=`ps -fe|grep $PROG|egrep -v grep|awk '{print $2}'`
	RETVAL=$?
	if [ "$RETVAL" = 0 ]
	    then touch $LOCK_FILE
	    echo $myPid >$PID_FILE
	fi
	echo
}

stop() {
	echo -n $"Stopping $prog: "
	if [ -n "`pidfileofproc $PROG`" ] ; then
	    killproc $PROG -TERM
	else
	    failure $"Stopping $prog"
	fi
	RETVAL=$?
	[ "$RETVAL" = 0 ] && rm -f $LOCK_FILE
	echo
}

case "$1" in
	start)
		start
		;;
	stop)
		stop
		;;
	restart)
		stop
		start
		;;
	status)
		status $PROG
		RETVAL=$?
		;;
	*)
		echo $"Usage: $0 {start|stop|restart|status}"
		RETVAL=1
esac
exit $RETVAL
